﻿using UnityEngine;
using System.Collections;
using Copy;
using ProtoBuf.Message;
using NetWork.Layer;


namespace UI
{
    public class UICopyEvent : MonoBehaviour
    {
        #region main panel
        public void OnClickMainLineTab()
        {
            GetComponent<UICopy>().SwitchCopyPanel(CopyType.MainLine);
        }

        public void OnClickGroupTab()
        {
            var str = TableTextBlo.GetText("not_open_complete_module");
            BoxManager.CreatePopupTextBox(str);
            return;
            //GetComponent<UICopy>().SwitchCopyPanel( CopyType.Group );
        }

        public void OnClickChapter()
        {
            GetComponent<UICopy>().ResetOptionStr();
        }

        public void OnClickLevel()
        {
            GetComponent<UICopy>().ResetOptionStr();
        }

        public void OnClickClose()
        {
            GetComponent<UICopy>().Close();
        }

        public void OnCampClick()
        {
            Debug.Log("[DBEUG] open camp page");

            PageManager.Instance.OpenPage("FormationPopupPage", "");
        }

        /// <summary>
        /// 挑战
        /// </summary>
        public void OnChallengeClick()
        {
            var chapterId = GetComponent<UICopy>().currentSelectionChapterId;
            var levelId = GetComponent<UICopy>().currentSelectionLevelId;

            var level = UICopyData.GetUILevelData(chapterId, levelId);

            if (!string.IsNullOrEmpty(level.level_open_id) &&
                !StaticData.storyData.isQuestFinished(level.level_open_id) &&
                !Story.StoryManager.Instance.ignorePreQuest)
            {
                BoxManager.CreateMessageBoxWithCofirmAndCancelButton(TableTextBlo.GetText("copy_need_open_task"), true, (b) =>
                 {
                     if (b)
                     {
                         StaticData.townNeedFindQuestTarget = "";
                         var questData = Dict.Blo.DictStoryBlo.GetQuest(StaticData.storyData.GetCurQuestId());
                         var town = Room.RoomManager.currentRoom as Room.RoomTown;
                         if(town!=null)
                         {
                             var self = town.charactorManager.GetSelfCharactor();
                             var npc = town.charactorManager.GetCharactor(questData.npcId);
                             if (self != null && npc != null)
                             {
                                 var selfai = self.ai as Room.RCAISelf;
                                 GetComponent<UICopy>().Close();
                                 selfai.GoToAndClick(npc);
                             }
                             else
                             {
                                 StaticData.townNeedFindQuestTarget = questData.npcId;
                                 GetComponent<UICopy>().Close();
                             }
                         }
                         else
                         {
                             StaticData.townNeedFindQuestTarget = questData.npcId;
                             GetComponent<UICopy>().Close();
                         }
                         
                     }
                     else
                     {
                     }
                 }, TableTextBlo.GetText("copy_tip"));
                return;
            }

            if (StaticData.playerData.IsHeroFull())
            {
                BoxManager.ShowHeroFull();
                return;
            }
            if (StaticData.playerData.IsEquipFull())
            {
                BoxManager.ShowEquipFull();
                return;
            }
            Story.StoryManager.Instance.OnCopyChallenge(levelId, _OnChallengeClick);
        }

        /// <summary>
        /// 挑战
        /// </summary>
        public void _OnChallengeClick()
        {

            var chapterId = GetComponent<UICopy>().currentSelectionChapterId;
            var levelId = GetComponent<UICopy>().currentSelectionLevelId;



            StaticData.currFightChapterId = chapterId;
            StaticData.currFightLevelId = levelId;
            if (!GameConfig.Instance.IsAssetFull && UICopyData.GetUIChapterData(chapterId).chapter_seq > 10)
            {
                BoxManager.CreatePopupTextBox(LanguageTool.GetTextNoUpdate(1046));
                return;
            }
            if (StaticData.playerData.Stamina < UICopyData.GetUILevelData(chapterId).level_power_cost)
            {
                string id = "item_002";

                PageManager.instance.OpenPage("BuyItemPage", "id=" + id);
                var buyPage = PageManager.instance.currentPage as BuyItemPage;
                buyPage.use = delegate
                {
                    if (StaticData.playerData.GetSimpleItemCount(id) > 0)
                    {
                        CSItemUse iUse = new CSItemUse();
                        iUse.costItem = new BaseResource();
                        iUse.costItem.id = id;
                        iUse.costItem.num = 1;

                        NetAPI.SendHttp(OpDefine.SCItemUse, iUse, (o, ok) =>
                        {
                            if (ok)
                            {
                                StaticData.playerData.GetSimpleGoods(id).num -= 1;
                                int stamina = Dict.DictDataManager.Instance.tableItemDao.GetById(id).stamina;
                                string powerStr = TableTextBlo.GetText("power");
                                BoxManager.CreatePopupTextBox(powerStr + "+" + stamina);
                                StaticData.playerData.Stamina += stamina;
                            }
                        });
                    }
                    else
                    {
                        BoxManager.CreatePopupTextBox(TableTextBlo.GetText("lack_of_props"));
                    }
                };

                buyPage.buy = delegate
                {
                    UIShopProduct product = null;
                    foreach (var it in StaticData.playerData.ItemShopProductList)
                    {
                        if (it.Value.productList[0].id == id)
                        {
                            product = it.Value;
                            break;
                        }
                    }

                    if (product != null)
                    {
                        CSUseAvoidPlunder uap = new CSUseAvoidPlunder();
                        uap.usedItem = product.productId;
                        NetAPI.SendHttp(OpDefine.CSUseAvoidPlunder, uap, (o, ok) =>
                        {
                            if (ok)
                            {
                                var ua = (SCUseAvoidPlunder)o.kBody;
                                StaticData.playerData.ResetAvoidPlunderTime(ua.avoidSurplusTime);
                                StaticData.playerData.Delete(ua.cost);
                                string str = TableTextBlo.GetText("today_can_buy_times");
                                string tip = string.Format(str, product.dayLeftTimes);
                                BoxManager.CreatePopupTextBox(tip);
                            }
                        });
                    }
                    else
                    {
                        //BoxManager.CreatePopupTextBox("无法购买商品");
                        Debug.Log("error:can't find product");
                    }
                };

            }
            else if (UICopyData.GetUILevelData(StaticData.currFightLevelId).level_curr_challenge >=
                UICopyData.GetUILevelData(StaticData.currFightLevelId).level_max_challenge)
            {
                /*string str = "resetChapterId=" + chapterId;
                str += "&resetLevelId=" + levelId;
                str += "&costRuby=" + UICopyData.GetUILevelData(StaticData.currFightLevelId).level_reset_cost_ruby;

                PageManager.instance.OpenPage("UICopyResetChanllangeCount", str);
                */

                BeginOpenResetLevelCost();
            }
            else
            {
                CSCopyEnter copyEnter = new CSCopyEnter();
                copyEnter.chapterId = StaticData.currFightChapterId;
                copyEnter.missionId = StaticData.currFightLevelId;

                ///先清空掉落
                //StaticData.willDrops.Clear();
                //StaticData.willBaseDrops.Clear();

                StaticData.missionScene = "";

                NetAPI.SendHttp(OpDefine.CSCopyEnter, copyEnter, (obj, ok) =>
                {
                    if (ok)
                    {
                        SCCopyEnter enter = (SCCopyEnter)obj.kBody;
                        StaticData.currFightTaskId = enter.taskId;
                        StaticData.boxs = enter.boxList;
                        StaticData.jobs = enter.jobList;
                        StaticData.missionScene = enter.sceneName;

                        ///StaticData.willDrops.AddRange(enter.priorResource);
                        //StaticData.willBaseDrops.AddRange(enter.priorResource);
                        PageManager.Instance.OpenPage("UICopyRunMap", "");
                    }
                });
            }
        }

        /// <summary>
        /// 扫荡
        /// </summary>
        public void OnSweepClick()
        {
            if (StaticData.playerData.IsHeroFull())
            {
                BoxManager.ShowHeroFull();
                return;
            }
            if (StaticData.playerData.IsEquipFull())
            {
                BoxManager.ShowEquipFull();
                return;
            }
            var chapterId = GetComponent<UICopy>().currentSelectionChapterId;
            var levelId = GetComponent<UICopy>().currentSelectionLevelId;

            StaticData.currFightChapterId = chapterId;
            StaticData.currFightLevelId = levelId;

            var level = UICopyData.GetUILevelData(levelId);
            if (level.level_inst_star < 5)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("copy_sweep_star_limit"));
                return;
            }

            if (StaticData.playerData.vip < Dict.Blo.DictConfigBlo.GetCopySweepVipLimit() && StaticData.playerData.level < Dict.Blo.DictConfigBlo.GetCopySweepLevelLimit())
            {
                var str = string.Format(TableTextBlo.GetText("Sweep_vipOrLevelLimit"), Dict.Blo.DictConfigBlo.GetCopySweepLevelLimit(), Dict.Blo.DictConfigBlo.GetCopySweepVipLimit());
                BoxManager.CreatePopupTextBox(str);
                return;
            }
            if (StaticData.playerData.Stamina < UICopyData.GetUILevelData(levelId).level_power_cost)
            {
                PageManager.instance.OpenPage("BuyItemPage", "id=item_002");
                var buyPage = PageManager.instance.currentPage as BuyItemPage;
                buyPage.use = delegate
                {
                    buyPage.Close();
                };

                buyPage.buy = delegate
                {
                    buyPage.Close();
                };
            }
            else if (UICopyData.GetUILevelData(StaticData.currFightLevelId).level_curr_challenge >=
                UICopyData.GetUILevelData(StaticData.currFightLevelId).level_max_challenge)
            {
                /*string str = "resetChapterId=" + chapterId;
                str += "&resetLevelId=" + levelId;
                str += "&costRuby=" + UICopyData.GetUILevelData(levelId).level_reset_cost_ruby;

                PageManager.instance.OpenPage("UICopyResetChanllangeCount", str);
                */

                BeginOpenResetLevelCost();

            }
            else
            {
                var times = GetComponent<UICopy>().currentSweepCount;
                if (times > 0)
                {
                    PageManager.Instance.OpenPage("UICopySweep", "count=" + times + "&chapterId=" + chapterId + "&levelId=" + levelId);
                }
            }
        }

        public void OnAwardClick()
        {
            var chapterId = GetComponent<UICopy>().currentSelectionChapterId;
            PageManager.Instance.OpenPage("UICopyAward", "chapterId=" + chapterId);
        }

        public void OnRankClick()
        {
            PageManager.Instance.OpenPage("RankPage", "type=1");
        }

        #endregion


        void BeginOpenResetLevelCost()
        {
            var resetInfo = new CSCopyGetResetInfo();
            resetInfo.chapterId = StaticData.currFightChapterId;
            resetInfo.missionId = StaticData.currFightLevelId;

            NetAPI.SendHttp(OpDefine.CSCopyGetResetInfo, resetInfo, (obj, ok) =>
            {
                if (ok)
                {
                    var info = (SCCopyGetResetInfo)obj.kBody;
                    OpenResetLevel(info.cost[0], info.remainResetCount);
                }
            });
        }


        void OpenResetLevel(BaseResource br,int lastTimes)
        {
            var ti = TableTextBlo.GetText("reset_level");
            var co = TableTextBlo.GetText("reset_level_content");

            var needCostDiamond = br.num;

            var contentTxt = string.Format(co, needCostDiamond, lastTimes); 

            BoxManager.CreateMessageBoxWithCofirmAndCancelButton(contentTxt, true, (b) => 
            {
                if(b)
                {
                    if (StaticData.playerData.diamond >= needCostDiamond)
                    {
                        CSCopyResetChallengeCount reset = new CSCopyResetChallengeCount();
                        reset.chapterId = StaticData.currFightChapterId;
                        reset.missionId = StaticData.currFightLevelId;
               
                        NetAPI.SendHttp(OpDefine.CSCopyResetChallengeCount, reset, (obj, ok) =>
                        {
                            if (ok)
                            {
                                StaticData.playerData.SubDiamond(needCostDiamond);
                                UICopyData.ResetCurrentLevelChallengeCount(StaticData.currFightLevelId);
                                var copyPage = PageManager.Instance.currentPage as UICopy;
                                if(copyPage!=null)
                                {
                                    copyPage.RefreshDropDetail();
                                }
                            }
                        });
                    }
                    else
                    {
                        Debug.Log("[DEBUG] need open recharge page");
                    }
                }

            }, ti);
        }

        #region network event

        public void GetPassedCopy()
        {
            NetAPI.SendHttp(OpDefine.CSCopyPassedInfo, new CSCopyPassedInfo(), (data, ok) =>
          {
              if (ok)
              {
                  SCCopyPassedInfo passedCopy = (SCCopyPassedInfo)data.kBody;
                  StaticData.copyData.SetPassedCopyInfo(passedCopy);

                  GetComponent<UICopy>().Refresh();
                  GetComponent<UICopy>().bossAndCook.RefreshBossCook();
              }
          });
        }

        public void GetCurrentCopy()
        {
            NetAPI.SendHttp(OpDefine.CSCopyCurrentInfo, new CSCopyCurrentInfo(), (data, ok) =>
           {
               if (ok)
               {
                   SCCopyCurrentInfo currentInfo = (SCCopyCurrentInfo)data.kBody;


                   StaticData.currFightChapterId = currentInfo.currentChapterId;
                   StaticData.currFightLevelId = currentInfo.currentMissionId;

                   UICopyData.OpenLevelAndChapterFunction(StaticData.currFightChapterId, StaticData.currFightLevelId);

                   GetComponent<UICopy>().RefreshOrNext();
                   GetComponent<UICopy>().bossAndCook.RefreshBossCook();
               }
           });
        }
        #endregion
    }
}